<!DOCTYPE html>
<html lang="en">
<head>
    <title>远程终端</title>
    <link rel="stylesheet" href="/static/xterm/node_modules/xterm/css/xterm.css" />
    <script src="/static/xterm/node_modules/xterm/lib/xterm.js"></script>
</head>
<body>
<div>
    <p style="position:absolute; padding: 0; right:0; margin-right:19px; text-align: center; z-index: 999">
        <button class="btn btn-danger " id="id-close-conn">
            <span class="ti-power-off"></span>
        </button>
    </p>
    <div id="terminal"></div>
</div>
<script src="/static/js/jquery.js"></script>
<script>
    //获取window的长宽
    function get_box_size() {
        let init_width = 9;
        let init_height = 17;

        let windows_width = $(window).width();
        let windows_height = $(window).height();
        return {
            cols: Math.floor(windows_width / init_width),
            rows: Math.floor(windows_height / init_height),
        }
    }

    //连接后端websocket
    function connect_ssh() {
        let cols = get_box_size().cols;
        let rows = get_box_size().rows;

        //根据div的大小初始化终端，待WebSocket连接上后，显示终端
        let term = new Terminal(
            {
                cols: cols,
                rows: rows,
                useStyle: true,
                cursorBlink: true,
                cursorStyle: 'underline',
                convertEol: true,
            }
        );

        let pwd = window.btoa("{{ ssh_info.password }}");

        //建立WebSocket连接
        let ssh_args = `user={{ ssh_info.user_name }}&host={{ ssh_info.ip }}&port={{ ssh_info.port }}&pwd=` + pwd;
        let ws_scheme = window.location.protocol === "https:" ? "wss" : "ws"; //获取协议
        let ws = new WebSocket(ws_scheme + '://' + window.location.host + '/wyh0282/wangyh/?' + ssh_args + `&width=${cols}&height=${rows}`);


        //打开websocket连接，并打开终端
        ws.onopen = function () {
            console.log('WebSocket建立连接，打开Web终端');
            term.open(document.getElementById('terminal'));
        };
        ws.onclose = function (e) {
            console.error('WebSocket关闭连接，关闭Web终端');
            window.close();
        };

        //读取服务器发送的数据并写入web终端
        ws.onmessage = function (e) {
            console.log('WebSocket接收消息，ssh交互中');
            let data = JSON.parse(e.data);
            console.log(data);
            let message = data['message'];
            if (data.flag === 'msg') {
                term.write(message);
            } else if (data.flag === 'fail') {
                term.write(message);  //连接ssh的异常提示
                swal(
                    {
                        title: "连接失败",
                        text: message,
                        type: "error",
                    });
                setTimeout(function () {
                    term.write(message);
                }, 5000);
            } else if (data.flag === 'user') {
                swal(
                    {
                        title: "消息",
                        text: message,
                        type: "info",
                    });
            } else if (data.flag === 'error') {
                swal(
                    {
                        title: "连接失败",
                        text: message,
                        type: "error",
                    });

                setTimeout(function () {
                    term.write(message);
                }, 5000);

            }

        };

        //向服务器发送数据
        term.onData(function (data) {
            //data为每个按键输入内容，例如按A，就传递给后端：{'flag': 1, 'data': 'a', 'cols': None, 'rows': None}
            let send_data = JSON.stringify({
                'flag': 'entered_key',
                'entered_key': data,
                'cols': null,
                'rows': null
            });
            //向WebSocket发送消息，也就是输入的每一个按键
            ws.send(send_data)
        });

        //终端右上角显示的关闭连接安装，当点击是，关闭ws
        $('#id-close-conn').click(function () {
            ws.close();
        });

        // 监听浏览器窗口, 根据浏览器窗口大小修改终端大小
        $(window).resize(function () {
            let cols = get_box_size().cols;
            let rows = get_box_size().rows;
            console.log(`更改显示终端窗口大小，行${rows}列${cols}`);
            let send_data = JSON.stringify({'flag': 'resize', 'cols': cols, 'rows': rows});
            ws.send(send_data);
            term.resize(cols, rows) //调整页面终端大小
        })
    }

    $(function () {
        connect_ssh()
    })
</script>
</body>
</html>
